import React from 'react';
import BaseComponent from '@/components/BaseComponent';
import styles from './index.less';
import { Card } from 'antd';

import SearchForm from './SearchForm';
import StandardTable from '@/components/StandardTable';
import { connect } from 'dva';
import { saveAs } from 'file-saver';

/**
 * 上报进度
 */
@connect(({ user, reportProgress, loading }) => ({
  currentUser: user.currentUser,
  data: reportProgress.data,
  isLoading: loading.effects['reportProgress/getPageData'],
  isDownloading: loading.effects['reportProgress/queryAllExportData'],
}))
class ReportProgress extends BaseComponent {
  /**初始数据列表标题字段 */
  columns_initial = [
    {
      title: '城市',
      key: 'city_name',
      dataIndex: 'city_name',
    },
    {
      title: '区县',
      key: 'region_name',
      dataIndex: 'region_name',
    },
    {
      title: '上报机构',
      key: 'institution_name',
      dataIndex: 'institution_name',
    },
    {
      title: '胃镜总量',
      key: 'total',
      dataIndex: 'total',
    },
    {
      title: '初始数据库临时库',
      key: 'detail_temporary_lib',
      dataIndex: 'detail_temporary_lib',
      children: [
        {
          title: '应报数',
          key: 'lsk_ybs',
          dataIndex: 'lsk_ybs',
        },
        {
          title: '上报进度%',
          key: 'lsk_sbjd',
          dataIndex: 'lsk_sbjd',
        },
        {
          title: '合格',
          key: 'lsk_hg',
          dataIndex: 'lsk_hg',
        },
        {
          title: '不合格',
          key: 'lsk_bhg',
          dataIndex: 'lsk_bhg',
        },
        {
          title: '合格率%',
          key: 'lsk_hgl',
          dataIndex: 'lsk_hgl',
        },
      ],
    },
    {
      title: '初始数据库正式库',
      key: 'detail_lib',
      dataIndex: 'detail_lib',
      children: [
        {
          title: '上报数',
          key: 'zsk_sbs',
          dataIndex: 'zsk_sbs',
        },
        {
          title: '上报进度',
          key: 'zsk_sbjd',
          dataIndex: 'zsk_sbjd',
        },
      ],
    },
    {
      title: '合计',
      key: 'total2',
      dataIndex: 'total',
      children: [
        {
          title: '应报数',
          key: 'hj_ybs',
          dataIndex: 'hj_ybs',
        },
        {
          title: '上报进度',
          key: 'hj_sbjd',
          dataIndex: 'hj_sbjd',
        },
        {
          title: '合格',
          key: 'hj_hg',
          dataIndex: 'hj_hg',
        },
        {
          title: '不合格',
          key: 'hj_bhg',
          dataIndex: 'hj_bhg',
        },
        {
          title: '合格率%',
          key: 'hj_hgl',
          dataIndex: 'hj_hgl',
        },
      ],
    },
  ];
  /**详情数据列表标题字段 */
  columns_detail = [
    {
      title: '城市',
      key: 'city_name',
      dataIndex: 'city_name',
    },
    {
      title: '区县',
      key: 'region_name',
      dataIndex: 'region_name',
    },
    {
      title: '上报机构',
      key: 'institution_name',
      dataIndex: 'institution_name',
    },
    {
      title: '初始数据正式库总量',
      key: 'total',
      dataIndex: 'total',
      width: 120,
    },
    {
      title: '详情数据库临时库',
      key: 'detail_temporary_lib',
      dataIndex: 'detail_temporary_lib',
      children: [
        {
          title: '应报数',
          key: 'lsk_ybs',
          dataIndex: 'lsk_ybs',
        },
        {
          title: '上报进度%',
          key: 'lsk_sbjd',
          dataIndex: 'lsk_sbjd',
        },
        {
          title: '合格',
          key: 'lsk_hg',
          dataIndex: 'lsk_hg',
        },
        {
          title: '不合格',
          key: 'lsk_bhg',
          dataIndex: 'lsk_bhg',
        },
        {
          title: '合格率%',
          key: 'lsk_hgl',
          dataIndex: 'lsk_hgl',
        },
      ],
    },
    {
      title: '详情数据库正式库',
      key: 'detail_lib',
      dataIndex: 'detail_lib',
      children: [
        {
          title: '上报数',
          key: 'zsk_sbs',
          dataIndex: 'zsk_sbs',
        },
        {
          title: '上报进度',
          key: 'zsk_sbjd',
          dataIndex: 'zsk_sbjd',
        },
      ],
    },
    {
      title: '合计',
      key: 'total2',
      dataIndex: 'total',
      children: [
        {
          title: '应报数',
          key: 'hj_ybs',
          dataIndex: 'hj_ybs',
        },
        {
          title: '上报进度',
          key: 'hj_sbjd',
          dataIndex: 'hj_sbjd',
        },
        {
          title: '合格',
          key: 'hj_hg',
          dataIndex: 'hj_hg',
        },
        {
          title: '不合格',
          key: 'hj_bhg',
          dataIndex: 'hj_bhg',
        },
        {
          title: '合格率%',
          key: 'hj_hgl',
          dataIndex: 'hj_hgl',
        },
      ],
    },
  ];

  constructor(props) {
    super(props);

    this.state = {
      //城市集合
      cities: [],
      //区县集合
      districtAndStreet: [],
      //搜索条件
      searchCondition: {},
      //初始化数据
      data: [],
      // 被选中的行
      selectedRows: [],
      // 被选中后的行的id
      selectedRowKeys: [],
      // 初始数据表头（1）/详情数据表头（2）
      initialDataTable: 1,
    };
  }

  /**项目初始化*/
  componentDidMount() {
    this.getAllCities().then(data => {
      this.getPageData(data);
    });
  }

  /**
   * 初始化数据
   * */
  getPageData = params => {
    this.execHttp('reportProgress/getPageData', {
      currentPage: 1,
      pageSize: 10,
      ...params,
    });
  };

  /**
   * 导出数据
   * */
  exportData = params => {
    if (this.props.isDownloading) {
      return;
    }
    const hide = this.loadingMessage('正在导出数据，请稍后...');
    this.execHttp('reportProgress/queryAllExportData', {
      ...params,
    })
      .then(res => {
        hide();
        saveAs(res, '上报进度汇总' + '.xlsx');
      })
      .catch(err => {
        hide();
      });
  };

  /**点击获取省下面的城市*/
  getAllCities = () => {
    return new Promise((resolve, reject) => {
      this.execHttp('orgsetting/getAllProvinceCity', {
        parentRegionCode: '340000',
        user: this.props.currentUser.id,
      }).then(resp => {
        if (resp && resp.success) {
          const {
            success,
            data: { list },
          } = resp;
          if (success) {
            this.setState(
              {
                cities: list,
              },
              () => {
                // list.length为1表示为地市疾控账户登录
                if (list && list.length == 1) {
                  this.searchform.setSelectedCity(list[0].id);
                  // 加载区县数据
                  this.getDistrictAndStreet(list[0].id);

                  resolve({ city_code: list[0].id });
                } else {
                  resolve({ city_code: '' });
                }
              }
            );
          }
        }
      });
    });
  };

  /**获取城市下的区街道信息*/
  getDistrictAndStreet = val => {
    this.execHttp('orgsetting/getDistrictAndStreet', {
      parentRegionCode: val,
    }).then(resp => {
      if (resp && resp.success) {
        const { success, data } = resp;
        if (success) {
          this.setState({
            districtAndStreet: data.list,
          });
        }
      }
    });
  };

  render() {
    const { data, isLoading } = this.props;
    const { initialDataTable } = this.state;

    return (
      <div className={styles.reportProgress}>
        <Card bordered={true} title={'上报进度'}>
          <SearchForm
            cityList={this.state.cities}
            initialDataTable={this.state.initialDataTable}
            districtAndStreetList={this.state.districtAndStreet}
            wrappedComponentRef={searchform => (this.searchform = searchform)}
            onSearchClick={this.handleOnSearchClick}
            onResetClick={this.handleOnResetClick}
            onExportClick={this.handleOnExportClick}
            OnSelectedCity={this.handleOnSelectedCity}
          ></SearchForm>
        </Card>
        <Card bordered={true} className={styles.contentBox}>
          <div>
            {initialDataTable && initialDataTable == 1 ? (
              <StandardTable
                bordered
                loading={isLoading}
                data={data}
                hasSelection={false}
                selectedRows={this.state.selectedRows}
                columns={this.columns_initial}
                onChange={this.handleTableChange}
                rowKey="id"
              />
            ) : (
              <StandardTable
                bordered
                loading={isLoading}
                data={data}
                hasSelection={false}
                selectedRows={this.state.selectedRows}
                columns={this.columns_detail}
                onChange={this.handleTableChange}
                rowKey="id"
              />
            )}
          </div>
        </Card>
      </div>
    );
  }

  handleTableChange = (pagination, filters, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.getPageData(params);
  };

  /**
   * 获取城市下的区街道信息
   * */
  handleOnSelectedCity = value => {
    if (value !== undefined) {
      this.getDistrictAndStreet(value);
    } else {
      this.setState({
        districtAndStreet: [],
      });
    }
  };

  /**
   * 导出按钮被点击
   * */
  handleOnExportClick = params => {
    this.exportData(params);
  };

  /**
   * 搜索按钮点击
   * */
  handleOnSearchClick = params => {
    const type = params['type'];
    if (type) {
      this.setState({
        initialDataTable: type,
      });
    }
    this.getPageData(params);
  };

  /**
   * 重置按钮点击
   * */
  handleOnResetClick = () => {
    this.setState({
      initialDataTable: 1,
    });
    this.getPageData({});
  };
}

export default ReportProgress;
